package com.durian.base.frame.fragment;

import com.durian.base.frame.dialog.CustomProgressDialog;
import com.durian.base.frame.dialog.ILoadingDialog;
import com.durian.base.utils.ToolUtils;
import com.kingja.loadsir.callback.Callback;
import com.kingja.loadsir.core.LoadService;
import com.kingja.loadsir.core.LoadSir;

/**
 * 说明：FragmentFrame
 * <p/>
 * 作者：fanly
 * <p/>
 * 类型：Class
 * <p/>
 * 时间：2019-06-27 10:43
 * <p/>
 * 版本：version 1.0
 */
public abstract class FragmentFrame extends BaseLazyFragment{

    protected ILoadingDialog  mLoadingDialog;
    protected LoadSir.Builder mLoadBuilder;
    protected LoadService     mLoadService;

    @Override
    protected void onFirstUserVisible() {
        if (isOpenLoadSir()){
            mLoadBuilder = createLoadSirBuilder();
            if (mLoadBuilder != null){
                addLoadSirCallBack(mLoadBuilder);
                LoadSir loadSir = mLoadBuilder.build();
                mLoadService = loadSir.register(setLoadSirTarget(),setOnReloadListener());
            }
        }
    }

    @Override
    protected void onUserInvisible() {

    }

    /****************************** 加载框 *********************************/

    public void showLoading() {
        showLoading(true);
    }

    public void showLoading(boolean isCancel) {
        dismissLoading();
        mLoadingDialog = setLoadingDialog();
        if (mLoadingDialog != null){
            mLoadingDialog.setCancel(isCancel).showDialog(getChildFragmentManager());
        }
    }

    public void dismissLoading() {
        if (mLoadingDialog != null && mLoadingDialog instanceof CustomProgressDialog) {
            CustomProgressDialog progressDialog = (CustomProgressDialog) mLoadingDialog;
            if (progressDialog.getOwnerActivity() != null && !progressDialog.getOwnerActivity().isFinishing()) {
                progressDialog.dismiss();
            }
        }
        mLoadingDialog = null;
    }

    public ILoadingDialog setLoadingDialog() {
        if (ToolUtils.isNotFinish(getActivity())){
            CustomProgressDialog progressDialog = new CustomProgressDialog(getActivity());
            progressDialog.setOwnerActivity(getActivity());
            return progressDialog;
        }else {
            return null;
        }
    }


    /****************************** 加载框 *********************************/

    @Override
    public void onPause() {
        super.onPause();
        dismissLoading();
    }

    /**
     * 添加页面状态配置
     * @param builder
     */
    public void addLoadSirCallBack(LoadSir.Builder builder){}

    public boolean isOpenLoadSir(){
        return setLoadSirTarget() != null;
    }

    public Object setLoadSirTarget(){
        return null;
    }

    public Callback.OnReloadListener setOnReloadListener(){
        return null;
    }

    protected LoadSir.Builder createLoadSirBuilder(){
        return new LoadSir.Builder();
    }

}
